'use client';

import type { ICreateSectionGroupBody, IDifference } from '@/interfaces';
import type { TBody } from '@/types';
import { createSectionGroup } from '@/services/api';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
  type ChangeEvent,
  type FormEvent,
  useContext,
  useEffect,
  useState,
} from 'react';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import { cleanFormData, getDiffData, getFilterData, isEmpty } from '@/lib/tool';
import { SectionGroupAdminContext } from '@/contexts/admin/forum/sectionGroup';

export default function CreateSectionGroupAdminPage() {
  const { show } = useToast();
  const [form, setForm] = useState({
    name: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const context = useContext(SectionGroupAdminContext);
  const queryClient = useQueryClient();

  const createSectionGroupMutation = useMutation(
    async (variables: TBody<ICreateSectionGroupBody>) => {
      await createSectionGroup(variables);
    },
  );

  useEffect(() => {
    const differences = diff(
      {
        name: '',
      },
      form,
    );
    setDifferenceData(differences);
  }, [form]);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'DANGER',
          message: '新增版块组失败，数据不存在',
        });
        return;
      }

      await createSectionGroupMutation.mutateAsync({
        data: {
          name: body.name,
        },
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      createSectionGroupMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setForm(cleanFormData(form));
    setDifferenceData([]);
  }

  function checkForm() {
    const { name } = form;

    if (!name) {
      throw '版块组名称不能为空';
    }
  }

  function onChange(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  function onClickReturn() {
    if (typeof context.setIsCreate === 'function') {
      if (context.queryKey) {
        try {
          queryClient.refetchQueries(
            { queryKey: context.queryKey },
            { throwOnError: true },
          );
        } catch (e) {
          show({
            type: 'DANGER',
            message: e,
          });
        }
      }

      context.setIsCreate(false);
    }
  }

  return (
    <div className="row">
      <div className="col">
        <div className="card">
          <div className="card-header bg-transparent text-muted">
            <div className="row row-cols-auto justify-content-between">
              <div className="col">
                <div>
                  <i className="bi bi-plus-lg me-2"></i>
                  新增版块组
                </div>
              </div>
              <div className="col">
                <div>
                  <i
                    onClick={onClickReturn}
                    className="bi bi-arrow-return-left cursor-pointer text-primary"
                  ></i>
                </div>
              </div>
            </div>
          </div>
          <div className="card-body">
            <form onSubmit={onSubmit} className="vstack gap-4">
              <div>
                <label className="form-label">名称</label>
                <input
                  type="text"
                  name="name"
                  value={form.name}
                  onChange={onChange}
                  className="form-control"
                  aria-describedby="name"
                  placeholder="请输入版块组名称"
                />
              </div>

              <button
                type="submit"
                disabled={createSectionGroupMutation.isLoading}
                className="btn btn-primary w-25 my-4"
              >
                {createSectionGroupMutation.isLoading && (
                  <span
                    className="spinner-border spinner-border-sm me-2"
                    role="status"
                    aria-hidden="true"
                  ></span>
                )}
                保存
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}
